package tech.mhuang.pacebox.core.plugin;

import tech.mhuang.pacebox.core.sugar.Attempt;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;

/**
 * 插件类加载
 *
 * @author mhuang
 * @since 1.1.7
 */
public class PluginClassLoader extends URLClassLoader {

    /**
     * 创建jar包到插件
     *
     * @param jarFile jar文件
     * @return
     */
    public static PluginClassLoader create(File jarFile) {
        return create(getSystemClassLoader(), jarFile);
    }

    /**
     * 创建jar包到插件
     *
     * @param parent  插件使用的classloader
     * @param jarFile jar文件
     * @return 结果
     */
    public static PluginClassLoader create(ClassLoader parent, File jarFile) {
        return Attempt.supply(() -> {
            URL[] urls = new URL[]{jarFile.toURI().toURL()};
            return new PluginClassLoader(urls, parent);
        }).get();
    }

    public PluginClassLoader(URL[] urls, ClassLoader parent) {
        super(urls, parent);
    }

    public PluginClassLoader(URL[] urls) {
        super(urls);
    }

    public PluginClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
        super(urls, parent, factory);
    }
}
